package ecut;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBCDemo {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        System.out.println("注册驱动成功");

        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println(connection);

        //更新操作
        String sql = "update user set password=? where username=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, "12345");
        preparedStatement.setString(2, "王五");
        preparedStatement.executeUpdate();

        //增加操作
        sql = "INSERT INTO user values (?,?)";
        PreparedStatement insertStatement = connection.prepareStatement(sql);
        insertStatement.setString(1, "李四");
        insertStatement.setString(2, "wangwu");
        insertStatement.executeUpdate();

        //查询操作
        JDBCDemo jdbcDemo = new JDBCDemo();
        jdbcDemo.selectMethod(connection);

        //删除操作
        sql = "delete from user where username=?";
        PreparedStatement deleteStatement = connection.prepareStatement(sql);
        deleteStatement.setString(1, "李四");
        deleteStatement.executeUpdate();

        System.out.println("========删除后=======");

        jdbcDemo.selectMethod(connection);
    }

    public void selectMethod(Connection connection) throws Exception {
        String sql = "select * from user";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            System.out.println("username：" + resultSet.getString("username"));
            System.out.println("password：" + resultSet.getString("password"));
        }
    }
}
